<?php

namespace Addons\OaSystem\Controller;

use Think\ApiBaseController;

class ApiApprovalFlowProcessController extends ApiBaseController
{
    var $openid;
    var $appid;
    var $cur_emp_id;
    var $initial_check_pass;
    public function __construct() {
        $this->initial_check_pass = false;
        parent::__construct ();
        $this->openid = get_openid();
        $this->appid = get_app_info()['appid'];
        if($this->openid == -1){
            $return['errcode'] = '40003';
            echo api_return ( $return['errcode'],null,error_msg( $return) );
            exit;
        }
        $map['userid'] = $this->mid;

        $userEmp = M('OaUserEmployee')->where($map)->find();
        if(empty($userEmp)){
            $return['errcode'] = '50001';
            echo api_return ( $return['errcode'],null,error_msg( $return,"找不到对应的员工号") );
            exit;
        }
        $this->cur_emp_id = $userEmp['emp_id'];
        $this->initial_check_pass = true;
    }

    public function GetApplicationTypes(){
        // echo $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
        // $data=array("min"=>0,"max"=>5001);
        // var_dump(json_encode($data) );
        $map['appid'] =$this->appid;
        $res = M('OaApplyType')->where($map)->select();
        echo api_return( 0,$res);
    }
    private function find_first_step($operations,$applyer) {
        $empInfo = M('OaEmployee')->where(array('id'=>$applyer))->find();
        $dept = D('OaDeptView')->where(array('id'=>$empInfo['dept_id']))->find();
        $dutyId = $empInfo['duty_id'];
        // $deptId = $dept['id'];
        // $tar_deptId =  findTargetDetp($dept,2);

        $dutyLvl = M('OaDuty')->where(array('id'=>$dutyId))->getField('level');
        // $map['role_level'] = $dutyLvl;
        $map['emp_id'] = $applyer;
        // $map['role_deptid'] = $deptId; // array('in',array($deptId,$tar_deptId));
        // var_dump($map);
        $roles = D('OaUserRoleView')->where($map)->select();
        // var_dump($roles);
        // var_dump($operations);
        $index = false;
        $tmpRole = $roles[0];
        foreach ($roles as $role) {
            $tmp = array_search(intval($role['role_id']),$operations);
            if ($tmp !== false) {
                // var_dump($role);
                if($dutyLvl == $role['role_level']) {
                    $index = $tmp + 1;
                    // var_dump('find_first_step find');
                    break;
                }else if ($tmpRole['role_level'] < $role['role_level']){
                    $tmpRole = $role;
                    $index = $tmp + 1;
                }
            }
        }
        // var_dump($index);
        return $index;
    }

    private function GetApprvalFlowInRoleCase ($operations,$attr,$applyer) {
        $flowRoles = array();

        $tmp['name'] = M('OaRole')->where(array('id'=>$operations[0]))->getField('name');
        $tmp['step'] = 1;
        array_push($flowRoles,$tmp);

        $step = $this->find_first_step($operations,$applyer);
        /*
        if ($step != 1) {
            $tmp['id'] = $operations[$step-1];
            $tmp['name'] = M('OaRole')->where(array('id'=>$tmp['id']))->getField('name');
            $tmp['step'] = $step;
            array_push($flowRoles,$tmp);
        }*/

        for($i = $step,$j=1; $i < count($operations); $i++){
            $tmp = whoHasTheRole($operations[$i]);
            if ($tmp['count'] == 0) {
                continue;
            }else {
                $data['id'] = $operations[$i];
                $data['name'] = M('OaRole')->where(array('id'=>$operations[$i]))->getField('name');
                $data['step'] = $i+1;
                array_push($flowRoles,$data);
                $j++;
            }
            if ($j >= $attr['len']){
                break;
            }
        }
        $data['id'] = $operations[count($operations)-1];
        $data['name'] = M('OaRole')->where(array('id'=>$data['id']))->getField('name');
        $data['step'] = count($operations);
        array_push($flowRoles,$data);
        // var_dump('GetApprvalFlowInRoleCase');
        // var_dump($flowRoles);
        // var_dump('GetApprvalFlowInRoleCase 1');
        return $flowRoles;
    }

    private function GetApprvalFlowInRoleCaseOfOperation($operations) {
        $flowRoles = array();
        for($i = 0; $i < count($operations); $i++){
            $data['id'] = $operations[$i];
            $data['name'] = M('OaRole')->where(array('id'=>$operations[$i]))->getField('name');
            $data['step'] = $i+1;
            array_push($flowRoles,$data);
        }
        return $flowRoles;
    }
    public function GetApprovalFlow() {
        $map['appid'] = $this->appid;
        if(empty(I('get.flow_id'))){
            $res = M('OaProcessFlow')->where($map)->select();
            echo api_return( 0,$res);
        }else{
            $map['id'] = I('flow_id');
            $res = M('OaProcessFlow')->where($map)->find();
            $flowAttr = json_decode($res['attr'],true);
            if (empty($flowAttr['type'])) {
                $data = [];
                if(!empty($res)){
                    $flowNodes = json_decode($res['operations']);
                    foreach ($flowNodes as $flow){
                        $tmp['id'] = $map['id']= intval($flow);
                        $tmp['name'] = M('OaNode')->where($map)->getField('name');
                        array_push($data,$tmp);
                    }
                }
                $res['operations'] = $data;
                echo api_return( 0,$res);
            } else if ($flowAttr['type'] == 'OaRole') {
                $apply = M('OaApplication')->where(array('id'=>I('apply_id')))->find();

                $operations = json_decode($res['operations']);
                // var_dump($operations);
                if($flowAttr['type'] == 1) {
                    $res['operations'] = $this->GetApprvalFlowInRoleCase($operations,$flowAttr,$apply['applyer']);
                }else{
                    $res['operations'] = $this->GetApprvalFlowInRoleCaseOfOperation($operations);
                }

                echo api_return( 0,$res);
            }

        }
    }

    public function GetFlowNode() {
        $map['appid'] = $this->appid;
        if(empty(I('node_id'))){
            $res = M('OaNode')->where($map)->select();
            echo api_return( 0,$res);
        }else{
            $map['id'] = I('node_id');
            $res = M('OaNode')->where($map)->find();
            echo api_return( 0,$res);
        }
    }

    public function LaunchApplication() {
        if(!$this->initial_check_pass) {
            return;
        }
        $data = json_decode(I('apply_data'),true);
        $map['id'] = $data['type'];
        $type = M('OaApplyType')->where($map)->find();
        $dep_map['id'] = $data['dept_id'];
        $dep = M('OaDept')->where($dep_map)->find();
        $res = create_one_application($data,$type,$dep,$this->cur_emp_id,$this->appid,$apply_id);
        if($res === true){
            $apply_map['id'] = $apply_id;
            $res = M('OaApplication')->where($apply_map)->find();
            echo api_return( 0,$res);
        }else{
            echo api_return( $res['errcode'],$res['data'],$res['errmsg']);
        }
    }

    public function DeleteApplyItem(){
        $apply_map['id'] = I('apply_id');
        if(empty($apply_map['id'])){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],false,error_msg($return,'apply_id 不能为空'));
            return;
        }
        $apply = M('OaApplication')->where($apply_map)->find();
        if (empty($apply)){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],false,error_msg($return,'找不到数据'));
            return;
        }
        if ($apply['step'] != 1){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],false,error_msg($return,'审批过程中不能修改'));
            return;
        }
        $map['application_id'] = I('apply_id');
        $map['id'] = I('applyItem_id');
        $res = M('OaApplyItem')->where($map)->delete();
        echo api_return( 0,$res);
    }

    public function UpdateApplyItem() {
        $apply_map['id'] = I('apply_id');
        if(empty($apply_map['id'])){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],false,error_msg($return,'apply_id 不能为空'));
            return;
        }
        $apply = M('OaApplication')->where($apply_map)->find();
        if (empty($apply)){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],false,error_msg($return,'找不到数据'));
            return;
        }
        if ($apply['step'] != 1){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],false,error_msg($return,'审批过程中不能修改'));
            return;
        }

        $data = json_decode(I('data'),true);
        $res = false;

        if(!empty(I('applyItem_id'))){
            $map['application_id'] = I('apply_id');
            $map['id'] = I('applyItem_id');
            $res = M('OaApplyItem')->where($map)->save($data);
            if($res !== false){
                $res = $data['id'];
            }
        }else{
            $res = M('OaApplyItem')->add($data);
        }

        if($res === false){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],$res,error_msg($return));
        }else{
            echo api_return( 0,$res);
        }
    }

    public function ApplicationDone()
    {
        if(!$this->initial_check_pass) {
            return;
        }
        $apply_id= I('apply_id');
        $comment = I('comment');
        $formId = I('formId');
        $res = appliction_done($apply_id,$comment,$this->cur_emp_id,$this->appid,$formId);
        if ($res === true){
            echo api_return(0,null);
        }else{
            echo api_return( $res['errcode'],$res['data'],$res['errmsg']);
        }
    }
    /*
    private function goto_next_step($apply_data,$old_data,$comment) {
        $map['id'] = $apply_data['flow_id'];
        $process = M('OaProcessFlow')->where($map)->find();

        $res = checkApprovalHop($apply_data,$old_data,$this->cur_emp_id);
        if($res['errcode'] !== 0){
            echo api_return($res['errcode'],null,$res['msg']);
            return false;
        }

        $operation = json_decode($process['operations']);
        if (false == checkNodeAccessRight($operation[$old_data['step']-1],$this->cur_emp_id))
        {
            $return['errcode'] = '50002';
            echo api_return($return['errcode'],$res,error_msg($return,' 没有访问权限'));
            return false;
        }

        if (count($operation) < $apply_data['step']){
            $return['errcode'] = '61451';
            $return['msg'] = error_msg($return,'step 数据错误,超出流程步数');
            echo api_return($return['errcode'],null,$return['msg']);
            return false;
        }

        $apply_data['approver'] = 0;
        $apply_data['is_read'] = false;
        $apply_data['hops'] = $old_data['hops']+1;
        $apply_map['id'] = $apply_data['id'];
        if(M('OaApplication')->where($apply_map)->save($apply_data)){
            $log['appid'] = $this->appid;
            $log['emp_id'] = $apply_data['applyer'];
            $log['application_id'] = $apply_data['id'];
            $log['approver'] = $old_data['approver'];
            $log['step'] = $old_data['step'];
            $log['hop'] = $old_data['hops']+1;
            $log['status'] = 1;
            $log['result'] = true;
            $log['comment'] = $comment;
            $log['time'] = NOW_TIME;
            $log['approver_name'] = M('OaEmployee')->where('id',$log['approver'])->getField('name');
            $log['node_name'] = M('OaNode')->where('id',$operation[$log['step']-1])->getField('name');
            M('OaProcessLog')->add($log);
            $emplist = getWhoHasTheRightAccessThisNode($operation[$apply_data['step']]);
            foreach ( $emplist as $emp) {
                D('OaEmpMsg')->sendmsg(3,$emp,msg_reimbursementInPool($apply_data['apply_no']));
            }
        }

        return true;
    }

    private function approvalFail_goback($comment,$old_data){
        $map['id'] = $old_data['flow_id'];
        $process = M('OaProcessFlow')->where($map)->find();
        $operation = json_decode($process['operations'],true);
        $node_id = $operation[$old_data['step']-1];
        if (false == checkNodeAccessRight($node_id,$this->cur_emp_id))
        {
            $return['errcode'] = '50002';
            echo api_return($return['errcode'],$res,error_msg($return,' 没有访问权限'));
            return false;
        }
        $nd_map['id'] = $node_id;
        $node = M('OaNode')->where($nd_map)->find();
        if(empty($node['failback'])){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],$res,error_msg($return,' Node没有配置回退功能'));
            return false;
        }
        $old_step = $old_data['step'];
        $log_map['step'] = $node['failback'];
        $log_map['application_id'] = $old_data['id'];
        $log_map['appid'] = $this->appid;
        $logs = M('OaProcessLog')->where($log_map)->order('hop desc')->select();
        if(empty($logs)){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],$res,error_msg($return,' Log查找不到对应的记录'));
            return false;
        }
        $back_log = $logs[0];
        $old_data['step'] = $node['failback'];
        $old_data['approver'] = $back_log['approver'];
        $old_data['hops'] = $old_data['hops'] + 1;
        $old_data['is_read'] = true;
        $apply_map['id'] = $old_data['id'];
        if(M('OaApplication')->where($apply_map)->save($old_data)) {
            $log['appid'] = $this->appid;
            $log['emp_id'] = $old_data['applyer'];
            $log['application_id'] = $old_data['id'];
            $log['approver'] = $old_data['approver'];
            $log['step'] = $old_step;
            $log['hop'] = $old_data['hops'];
            $log['status'] = 1;
            $log['result'] = false;
            $log['comment'] = $comment;
            $log['time'] = NOW_TIME;
            $log['approver_name'] = M('OaEmployee')->where('id',$log['approver'])->getField('name');
            M('OaProcessLog')->add($log);
            D('OaEmpMsg')->sendmsg(3,$log['approver'],msg_reimbursementRefused($old_data['apply_no']));
        }

        return true;
    }
    */

    public function UpdateApplication() {
        if(!$this->initial_check_pass) {
            return;
        }
        $cur_step = I('get.step');
        $comment = I('comment');
        $formId = I('formId');

        $apply_data = json_decode(I('data'),true);
        $go_next = empty(I('go_next'))?0:I('go_next');

        $res = process_reimburse_apply($apply_data,$cur_step,$go_next,$comment,$this->cur_emp_id,$this->appid,$formId);
        if($res !== true){
            echo api_return( $res['errcode'],$res['data'],$res['errmsg']);
        }else{
            $apply_map['id'] = $apply_data['id'];
            $ret_data = M('OaApplication')->where($apply_map)->find();
            echo api_return( 0,$ret_data);
        }

    }

    public function GetApplicationList() {
        if(empty(I('applyer'))){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],$res,error_msg($return));
        }
        if(!empty(I('type'))){
            $map['type'] = I('type');
        }
        if(!empty(I('status'))) {
            $map['status'] = intval(I('status'));
        }

        $map['applyer'] = I('applyer');
        $map['is_del'] = array("neq",1);;
        if (!empty(I('apply_id'))){
            $map['id'] = I('apply_id');
        }
        if (!empty(I('apply_id'))){
            $map['apply_id'] = I('apply_id');
        }

        if (!empty(I('page'))){
            $p = I('page');
            $row = empty(I('row'))?20:I('row');
            $data = M('OaApplication')->where($map)->order('submit_date desc')->page($p,$row)->select();
        }else{
            $data = M('OaApplication')->where($map)->order('submit_date desc')->select();
        }

        echo api_return(0,$data);
    }

    public function GetApprovallingList(){
        if(empty(I('approver'))){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],$res,error_msg($return));
        }
        if(!empty(I('type'))){
            $map['type'] = I('type');
        }
        $map['approver'] = I('approver');
        $map['is_del'] = array("neq",1);
        if (!empty(I('apply_id'))){
            $map['apply_id'] = I('apply_id');
        }
        // $map['status'] = empty(I('filter'))?0:I('filter');
        $map['status'] = array('neq',1);
        $map['step'] = array("gt",1);
        if (!empty(I('page'))){
            $p = I('page');
            $data = M('OaApplication')->where($map)->order('submit_date desc')->page($p,20)->select();
        }else{
            $data = M('OaApplication')->where($map)->order('submit_date desc')->select();
        }
        echo api_return(0,$data);
    }

    public function GetMyApprovalBufferPool(){
        $applications = getMyApprovalBufferPool($this->cur_emp_id,3);
        $attendenApplies = getAttendanceBufferPool($this->cur_emp_id);
        $applications =  array_merge ($applications,$attendenApplies);
        array_multisort(array_column($applications, 'submit_date'), SORT_DESC, $applications);
        echo api_return(0,$applications);
    }

    public function GetMyApprovedList(){
        $log_map['approver'] = $this->cur_emp_id;
        $log_map['step'] = array('gt',1);

        $data = M('OaProcessLog')->where($log_map)->order('time desc')->field('application_id')->select();
        $data = array_column($data, 'application_id');
        $data = array_unique($data);

        $map['id'] = array('in',$data);
        $map['is_del'] = array("neq",1);
        $tmps = Array();
        if (!empty(I('page'))){
            $p = I('page');
            $row = empty(I('row'))?20:I('row');
            $len = D('OaApplicationView')->where($map)->count();
            $tmps = D('OaApplicationView')->where($map)->order('submit_date desc')->page($p,$row)->select();
            $data['count'] = $len;
            $data['data'] = $tmps;
            echo api_return(0,$data);
        }else{
            $tmps = D('OaApplicationView')->where($map)->order('submit_date desc')->select();
            echo api_return(0,$tmps);
        }
    }

    public function GetMyApprovedAndDoneList(){
        $log_map['approver'] = $this->cur_emp_id;
        $data = Array();

        if (!empty(I('page'))){
            $p = I('page');
            $data = M('OaProcessLog')->where($log_map)->order('time desc')->page($p,20)->field('application_id')->select();
        }else{
            $data = M('OaProcessLog')->where($log_map)->order('time desc')->field('application_id')->select();
        }

        $data = array_column($data, 'application_id');
        $data = array_unique($data);

        $map['status'] = true;
        $map['id'] = array('in',$data);
        $tmps = D('OaApplicationView')->where($map)->order('approve_date desc')->select();
        echo api_return(0,$tmps);
    }

    public function GetApplicationfull(){
        if (empty(I('apply_id'))){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],null,error_msg($return));
            return;
        }
        $map['id'] = I('apply_id');
        $data['application'] = M('OaApplication')->where($map)->find();
        $item_map['application_id'] = I('apply_id');
        $data['items'] = M('OaApplyItem')->where($item_map)->select();
        echo api_return(0,$data);
    }
    public function GetReimbursementStandard(){

        $standard = M('OaReimbursementStandard')->select();
        $data = array();
        foreach ($standard as $row){
            if(array_key_exists($row['province'],$data)){
                $tmp['normal'] = $row['normal'];
                $tmp['high_time'] = $row['high_time'];
                $tmp['high'] = $row['high'];
                $tmp['meals'] = $row['meals'];
                $data[$row['province']][$row['city']] = $tmp;
            }else{
                $tmp['normal'] = $row['normal'];
                $tmp['high_time'] = $row['high_time'];
                $tmp['high'] = $row['high'];
                $tmp['meals'] = $row['meals'];
                $city_tmp[$row['city']] = $tmp;
                $data[$row['province']][$row['city']]=$tmp;
            }
        }
        echo api_return(0,$data);
    }

    public function GetMeetingReimburseStandard(){
        $standard = M('oa_meeting_reimburse_standard')->find();
        echo api_return(0, $standard);
    }

    public function GetApplicationLog(){
        if (empty(I('apply_id'))){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],null,error_msg($return));
            return;
        }
        $map['appid'] = $this->appid;
        $map['application_id'] = I('apply_id');
        $logs = M('OaProcessLog')->where($map)->order('time desc')->select();
        echo api_return(0,$logs);
    }
}